<style type="text/css"> 
    @import "<?php echo base_url() ?>assets/third_party/dojo161/dojox/grid/enhanced/resources/claro/EnhancedGrid.css";
    @import "<?php echo base_url() ?>assets/third_party/dojo161/dojox/grid/enhanced/resources/tundra/EnhancedGrid.css";
    @import "<?php echo base_url() ?>assets/third_party/dojo161/dojox/grid/enhanced/resources/EnhancedGrid_rtl.css";
</style>

<script type="text/javascript">
    dojo.require("dijit.Dialog");
    dojo.require("dojox.grid.EnhancedGrid");
    dojo.require("dojox.grid.enhanced.plugins.Pagination");
    dojo.require("dojox.grid.enhanced.plugins.IndirectSelection");
    dojo.require("dojo.data.ItemFileWriteStore");
    dojo.require("dojox.grid.enhanced.plugins.Filter");
    dojo.require("dojox.grid.enhanced.plugins.Selector");
    dojo.require("dojox.grid.enhanced.plugins.Menu");
    dojo.require("dojox.grid.enhanced.plugins.DnD");
    dojo.require("dojox.grid.enhanced.plugins.Search");
    dojo.require("dojox.grid.enhanced.plugins.CellMerge");
    dojo.require("dijit.form.FilteringSelect");
    dojo.require('doh.runner');
    
    //tiền tệ
    formatCurrency = function(inDatum){
        return isNaN(inDatum) ? '...' : dojo.currency.format(inDatum, this.constraint);
    }
    //ngày tháng
    formatDate = function(inDatum){
        return dojo.date.locale.format(new Date(inDatum), this.constraint);
    }
    
    //lấy dữ liệu từ json
    var news_store = new dojo.data.ItemFileWriteStore({url: "<?php echo base_url() ?>admin/news/display_grid"});
    var user_store = new dojo.data.ItemFileReadStore({url: "<?php echo base_url() ?>admin/news/json_user_data"});

    var layout = [{ cells: [
                { field: "id_news", name:"ID news", datatype:"number", width: 2, editable: false, hidden: true},
                { field: "title", name:"Title",styles: 'text-align: center;', 
                    editable: true,
                    width: 10,
                    //                    type: dojox.grid.cells.Editor, editorToolbar: true
                    type: dojox.grid.cells.TextBox
                },
                { field: "content", name:"Nội dung", styles: 'text-align: center;',                    
                    formatter: function() { 
                        var src = "http://t1.gstatic.com/images?q=tbn:ANd9GcSGD8R8Wa4oNDlJWB0J9ca4UkIY5IzHabzEHELuZSrpHutuQkRgZg"; 
                        var img = "<img src=\"" + src + "\" />"; 
                        return img;
                    } , 
                    width: 5},
                { field: "image", name:"Image",styles: 'text-align: center;',
                    formatter: function(value) { 
                        var src = value; 
                        var img = '<img src="' + src + '" height="80px" />'; 
                        return img;
                    } , 
                    width: 8},
                { field: "meta_title", name:"Meta Title",styles: 'text-align: center;', 
                    editable: true,
                    width: 10,
                    type: dojox.grid.cells.Editor, editorToolbar: true
                },
                { field: "meta_description", name:"Meta Description",styles: 'text-align: center;', 
                    editable: true,
                    width: 10,
                    type: dojox.grid.cells.Editor, editorToolbar: true
                },
                { field: "meta_keywords", name:"Meta keyword",styles: 'text-align: center;', 
                    editable: true,
                    width: 10,
                    type: dojox.grid.cells.Editor, editorToolbar: true
                },
                { field: "posted_by",name:"Posted by",styles: 'text-align: center;', editable:true,
                    type: dojox.grid.cells._Widget,
                    widgetClass: dijit.form.FilteringSelect,
                    widgetProps: {store: user_store},
                    formatter: function(inDatum,inRowIndex){
                        var sName = "...";
                        var grid = dijit.byId("grid");
                        sName = grid.store.getValue(grid.getItem(inRowIndex), "display_name");
                        
                        user_store.fetchItemByIdentity({
                            identity: inDatum,
                            onItem: function(item){ 
                                if(item){
                                    sName = item.name[0];
                                }
                            }
                        }); 
                        
                        return sName;
                    },
                    width: 8},
                //                { field: "posted_by",name:"Posted by",styles: 'text-align: center;', editable:true, type: dojox.grid.cells.ComboBox, width: 10},
                { field: "posted_time", name:"Posted Date",styles: 'text-align: center;', 
                    editable: true,
                    width: 10,
                    type: dojox.grid.cells.DateTextBox,
                    formatter: formatDate,
                    constraint: {datePattern:'dd-MMM-yyyy',selector: "posted_time"}
                }
            ]
        }];
        
    var layout_no_image = [{cells: [
                { field: "id_news", name:"ID news", datatype:"number", width: 2, editable: false, hidden: true},
                { field: "title", name:"Title",styles: 'text-align: center;', 
                    editable: true,
                    width: 10,
                    type: dojox.grid.cells.TextBox
                },
                { field: "content", name:"Nội dung", styles: 'text-align: center;',
                    formatter: function() { 
                        var src = "http://t1.gstatic.com/images?q=tbn:ANd9GcSGD8R8Wa4oNDlJWB0J9ca4UkIY5IzHabzEHELuZSrpHutuQkRgZg"; 
                        var img = "<img src=\"" + src + "\" />"; 
                        return img;
                    } , 
                    width: 5},
                { field: "meta_title", name:"Meta Title",styles: 'text-align: center;', 
                    editable: true,
                    width: 10,
                    type: dojox.grid.cells.Editor, editorToolbar: true
                },
                { field: "meta_description", name:"Meta Description",styles: 'text-align: center;', 
                    editable: true,
                    width: 10,
                    type: dojox.grid.cells.Editor, editorToolbar: true
                },
                { field: "meta_keywords", name:"Meta keywords",styles: 'text-align: center;', 
                    editable: true,
                    width: 10,
                    type: dojox.grid.cells.Editor, editorToolbar: true
                },
                { field: "posted_by",name:"Posted by",styles: 'text-align: center;', editable:true,
                    type: dojox.grid.cells._Widget,
                    widgetClass: dijit.form.FilteringSelect,
                    widgetProps: {store: user_store},
                    formatter: function(inDatum,inRowIndex){
                        var sName = "...";
                        var grid = dijit.byId("grid");
                        sName = grid.store.getValue(grid.getItem(inRowIndex), "display_name");
                        
                        user_store.fetchItemByIdentity({
                            identity: inDatum,
                            onItem: function(item){ 
                                if(item){
                                    sName = item.name[0];
                                }
                            }
                        }); 
                        
                        return sName;
                    },
                    width: 8},
                //                { field: "posted_by",name:"Posted by",styles: 'text-align: center;', editable:true, type: dojox.grid.cells.ComboBox, width: 10},
                { field: "posted_time", name:"Posted Date",styles: 'text-align: center;', 
                    editable: true,
                    width: 10,
                    type: dojox.grid.cells.DateTextBox,
                    formatter: formatDate, 
                    constraint: {datePattern:'dd-MMM-yyyy',selector: "posted_time"}
                }
            ]
        }];
        
    var plugins = {
        menus: {
        },
        filter: {
            closeFilterbarButton: true,
            ruleCount: 0
        },
        selector: {
        },
        dnd: {
            //copyOnly: false
            dndConfig: {
                //Configure in a hierarchical manner.
                //Không cho remove cell
                cell: {
                    out: false, //This rule has lower priority, it'll be overwritten.
                    within: false
                }
            }
        },
        cellMerge: {
            //        "mergedCells": [
            //            {row: "3", start: 1, end: 10, major: 3}
            //        ]
        },
        search: {},
        pagination: {
            pageSizes: ["1", "25", "50", "100", "All"],	// Array, custom the items per page button
            //            itemTitle: "entrys", 	// String, custom the item' title of description
            description: "30%",	// boolean, custom whether or not the description will be displayed
            sizeSwitch: "260px",	// boolean, custom whether or not the page size switch will be displayed
            pageStepper: "30em",	// boolean, custom whether or not the page step will be displayed
            gotoButton: true,	// boolean, custom whether or not the goto page button will be displayed
            maxPageStep: 7,		// Integer, custom how many page step will be displayed
            position: "bottom"	// String, custom the position of the pagination bar
            // there're three options: top, bottom, both
            // ,descTemplate: "${1} ${0}" // A template of the current position description.
        },
        indirectSelection: {
            headerSelector:true,
            name: "Selection",
            width: "30px",
            styles: "text-align: center;"
        }
    };
    
    function view_id(){
        var items = grid.selection.getSelected();
        var ids = [];
        var cbs = [];
        var i = 0;
        if (items.length) {
            dojo.forEach(items, function(selectedItem) {
                ids[i] = grid.store.getValues(selectedItem, "id_news");
                cbs[i] = grid.store.getValues(selectedItem, "posted_by");
                i++;
            })
        }

        alert("Id news: "+ids.toString());
        alert("Posted by: "+cbs.toString());
    }
    
    var cellEditClick = function(e) {
        if(e.cellIndex == 3){
            var myDialog = new dijit.Dialog({
                title: "Edit content news",
                style: "width: 600px;height:450px;"
            });

            var main = dojo.create("div", {
                //            innerHTML: "Update content news: ",
                id: "mainCon",
                style: "text-align:center"
            });
            var c = "...";
            c = grid.store.getValue(grid.getItem(e.rowIndex), "content");
            var editor = new dijit.Editor({
                value: c.toString()
            });

            var cancelBtn = new dijit.form.Button({
                label: "Cancel",
                style: "padding-top:25px;"
            });

            dojo.connect(cancelBtn, "onClick", function() {
                myDialog.destroy();
            });

            var submitBtn = new dijit.form.Button({
                label: "OK",
                style: "padding-left:15px;padding-top:25px;"
            });
            
            dojo.connect(submitBtn, "onClick", function() {
                grid.store.setValue(grid.getItem(e.rowIndex), 'content', editor.value);
                myDialog.destroy();
            });

            main.appendChild(editor.domNode);
            main.appendChild(cancelBtn.domNode);
            main.appendChild(submitBtn.domNode);

            myDialog.attr('content', main);
            myDialog.startup();
            myDialog.show();
        }
    }
    
    var load_sort = [];
    var size_store = 0;
    news_store.fetch({query: {}, onComplete: function (items, request) {
            size_store = items.length;  
            for (i = 0; i < items.length; i++) {
                load_sort[i] = news_store.getValue(items[i], "id_news");
            }            
        }, start: 0, count: 0});
    
    dojo.addOnLoad(function() {    
        grid.onApplyEdit = function (index) {
            alert(index);
        }
         
        // cell tooltip
        dojo.connect(grid, "onCellDblClick", cellEditClick);
        var cellEditClick1 = function(value, rowIndex,cellIndex){
            alert("Cell: "+cellIndex);
            alert("Row: "+rowIndex);
            alert("Value: "+value);
            alert(grid.edit.isEditRow(rowIndex));
        };
        dojo.connect(grid, "onApplyCellEdit", cellEditClick1);
        
    });
    
    // ==========================================================================
    // UI Action
    // ==========================================================================
    addRow = function(){
        news_store.newItem({
            id_news: 4,
            title: 'new',
            content: 'new',
            meta_title: 'new',
            meta_description: 'new',
            meta_keywords: 'new',
            posted_by: 1,
            posted_time: new Date()
        });
        
        
    }
    //toggleLayout
    var flag = false;
    toggleStructure = function() {
        flag = !flag;
        //	grid.scrollToRow(0);
        grid.set('structure', flag ? layout_no_image : layout);
    }
    
    function removeSelected(){
        grid.removeSelectedRows();
    }
    
    function sort_array(){
        alert(grid.rowsPerPage);
        var ids_sort = [];
        for (i = 0; i < size_store; i++) {
            ids_sort[i] = news_store.getValue(grid.getItem(i), "id_news");
        }
        alert(load_sort);
        alert(ids_sort);
        return ids_sort;
    }
    ////////////////////////////////////////////////
    
    
</script>
<div id="gridContainer">
    <input type='button' value='View ID' onclick='view_id()'/>
    <input type='button' value='Add row' onclick='addRow()'/>
    <input type='button' value='Struc' onclick='toggleStructure()'/>
    <button onclick="removeSelected()">Remove Selected</button>&nbsp;&nbsp;
    <button onclick="sort_array()">Apply Edit</button>&nbsp;&nbsp;
    <div id="grid"  jsId="grid" dojoType="dojox.grid.EnhancedGrid" 
         store="news_store" structure="layout" 
         plugins="plugins" escapeHTMLInData="false"
         clientSort="true" autoRender="true">
    </div>
</div><br/>
</body>